﻿using Com.Lancetinc.Evs.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Com.Lancetinc.Evs.Cameras
{
    public static class WhiteBalanceConfigHelper
    {
        private static readonly NLog.ILogger Logger = NLog.LogManager.GetCurrentClassLogger();

        public static WhiteBalanceValue GetDefaultValue(string endoscopicTypeCode)
        {
            try
            {
                var line = AppConfigHelper.GetWhiteBalanceConfig(endoscopicTypeCode);
                return ParseWhiteBalance(line);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        private static WhiteBalanceValue ParseWhiteBalance(string line)
        {
            if (line == null)
            {
                return null;
            }
            WhiteBalanceValue ret = new WhiteBalanceValue();
            string[] ss = line.Split(',');
            if (ss.Length == 6)
            {
                int index = 0;
                ret.R = byte.Parse(ss[index++]);
                ret.RGain = byte.Parse(ss[index++]);
                ret.G = byte.Parse(ss[index++]);
                ret.GGain = byte.Parse(ss[index++]);
                ret.B = byte.Parse(ss[index++]);
                ret.BGain = byte.Parse(ss[index++]);
            }
            return ret;
        }

        public static WhiteBalanceValue GetValue(string endoscopicTypeCode)
        {
            try
            {
                var lines = LoadConfig();
                if (lines == null)
                {
                    return null;
                }
                var prefix = endoscopicTypeCode + "=";
                var line = lines.FirstOrDefault(x => x.StartsWith(prefix));
                if (line != null)
                {
                    line = line.Substring(prefix.Length);
                }
                return ParseWhiteBalance(line);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return null;
            }
        }

        public static void SaveValue(string endoscopicTypeCode, WhiteBalanceValue value)
        {
            var lines = LoadConfig();
            var lineIndex = -1;
            var prefix = endoscopicTypeCode + "=";
            var lineValue = prefix + $"{value.R},{value.RGain},{value.G},{value.GGain},{value.B},{value.BGain}";
            if (lines != null)
            {
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].StartsWith(prefix))
                    {
                        lineIndex = i;
                        break;
                    }
                }
            }
            if (lineIndex > -1)
            {
                lines[lineIndex] = lineValue;
            }
            else if (lines == null)
            {
                lines = new string[] { lineValue };
            }
            else
            {
                lines = new List<string>(lines)
                {
                    lineValue
                }.ToArray();
            }
            var savePath = GetConfigFilePath();
            Directory.CreateDirectory(Path.GetDirectoryName(savePath));
            File.WriteAllText(savePath, string.Join(Environment.NewLine, lines));
        }

        private static string GetConfigFilePath()
        {
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            return Path.Combine(appDataPath, "Lancetinc", "Leinzett", "white_balance.ini");
        }

        internal static string[] LoadConfig()
        {
            var path = GetConfigFilePath();
            if (!File.Exists(path))
            {
                return null;
            }
            return File.ReadAllLines(path);
        }
    }
}
